package com.wuxy.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName PostUtil
 * @Description TODO
 * @Author wuxy
 * @DateTime 2018/9/25 09:20
 **/
public class FaceUtil {
    public static Map<String, String> getHeaders(String appId, String apiKey, String jsonParam)throws Exception {
        Map<String, String> headers = new HashMap<>();
        String time = new Date().getTime() /1000+ "";
        headers.put("X-Appid", appId);
        headers.put("X-CurTime", time);
        String XParam = Base64.getEncoder().encodeToString(jsonParam.getBytes("utf-8"));
        headers.put("X-Param",XParam );//"ewoJICAgICJhdXRvX3JvdGF0ZSI6ICJ0cnVlIiwKCX0="
        try {
            String param = toMd5(apiKey + time + XParam);
            headers.put("X-CheckSum", param);
            return headers;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return headers;
    }

    public static String toMd5(String encryptStr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(encryptStr.getBytes());
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }
            encryptStr = hexValue.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return encryptStr;
    }

    public static String readimg(String filePath){
        try {
            InputStream fileInputStream = new FileInputStream(filePath);

            byte[] b = new byte[fileInputStream.available()];//把所有的数据读取到这个字节当中
            //声明一个int存储每次读取到的数据
            int i = 0;
            //定义一个记录索引的变量
            int index = 0;
            //循环读取每个数据
            while((i=fileInputStream.read())!=-1){//把读取的数据放到i中
                b[index]=(byte) i;
                index++;
            }
            String result = Base64.getEncoder().encodeToString(b);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }
}
